package it.fuesi.synoutils.activities;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import it.fuesi.synoutils.R;
import it.fuesi.synoutils.activities.base.ADetailActivity;
import it.fuesi.synoutils.helpers.FormatHelper;
import it.fuesi.synoutils.helpers.LayoutHelper;
import it.fuesi.synoutils.model.config.SynoConfig;
import it.fuesi.synoutils.model.filestation.FileStationClientParameters;
import it.fuesi.synoutils.model.filestation.FileStationFile;
import it.fuesi.synoutils.services.cache.CacheService;
import it.fuesi.synoutils.services.client.ServiceClientFactory;
import it.fuesi.synoutils.services.tasks.filestation.DeleteFile;
import it.fuesi.synoutils.services.tasks.filestation.DownloadFile;
import it.fuesi.synoutils.services.tasks.filestation.RenameFile;


public class FileStationFileDetailActivity extends ADetailActivity<FileStationFile> {

    public static final int REQUEST_CODE = 103;
    public static final int RESULT_CODE_COPY = 140;
    public static final String RESULT_EXTRA_FILE = "RESULT_FILE";
    private static final String TAG = FileStationFileDetailActivity.class.getName();


    private ImageView mFileIcon;
    private TextView mFileName;
    private TextView mFileSize;
    private TextView mFilePath;
    private TextView mFileType;

    private DownloadFile mDownloadTask;

    @Override
    public int getLayoutId() {
        return R.layout.activity_file_station_file_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        mFileName = (TextView)findViewById(R.id.file_name);
        mFileSize = (TextView)findViewById(R.id.file_size);
        mFileIcon = (ImageView)findViewById(R.id.file_icon);
        mFilePath = (TextView)findViewById(R.id.file_path);
        mFileType = (TextView)findViewById(R.id.file_type);

        mFileName.setText(getItem().getName());
        mFileSize.setText(FormatHelper.formatFileSize(getItem().getSize()));
        mFilePath.setText(getItem().getPath());
        mFileType.setText(getItem().getType());

        if(getItem().isdir())
            mFileIcon.setImageResource(R.drawable.folder);
        else
            mFileIcon.setImageResource(R.drawable.document); //TODO: manage mime type
    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.file_station_file_detail, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_delete) {
            confirmDelete();
            return true;
        }else if(id == R.id.action_rename){
            promptRename();
            return true;
        }else if(id == R.id.action_download){
            downloadFile();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    private void downloadFile(){
        FileStationClientParameters params = new FileStationClientParameters();
        params.setFile_path(getItem().getPath());
        params.setName(getItem().getName());
        mDownloadTask = new DownloadFile(this);
        mDownloadTask.execute(params);
    }

    public void onDownloadFinished(){
        mDownloadTask = null;
    }


    private void promptRename(){
        final EditText edit = new EditText(this);
        edit.setText(getItem().getName());
        edit.setSelectAllOnFocus(true);
        new AlertDialog.Builder(this)
                .setTitle("Rename file")
                .setMessage("Rename file to:")
                .setView(edit)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        renameFile(edit.getText().toString());
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_info)
                .show();

    }

    private void renameFile(String newName){
        newName = newName.trim();
        if(newName.isEmpty()) return;
        if(newName.equals(getItem().getName())) return;

        FileStationClientParameters params = new FileStationClientParameters();
        params.setName(newName);
        params.setFile_path(getItem().getPath());
        params.setFolder_path(getItem().getParentPath());

        new RenameFile(this).execute(params);
    }

    private void confirmDelete(){
        new AlertDialog.Builder(this)
                .setTitle("Confirm delete")
                .setMessage("Delete file: " + getItem().getName() + " ?")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        deleteFile();
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_info)
                .show();
    }

    private void deleteFile(){
        final FileStationClientParameters params = new FileStationClientParameters();
        final String filePath = getItem().getPath();
        final String folderPath = filePath.substring(0, filePath.lastIndexOf("/"));
        params.setFile_path(getItem().getPath());
        params.setFolder_path(folderPath);
        new DeleteFile(this).execute(params);
    }



}
